<template>
  <div class="login-container">
    <div class="login-wrap f-c-cc">
      <div class="login-header f-r-sbc">
        <img src="@/assets/img/banner/banner-logo.png" @click="toPage('Home')" class="header-logo cursor" alt="" />
        <div class="btn-down f-r-cc cursor" @click="toPage('Downloads')">下载APP</div>
      </div>
      <div class="login-content f-r-sbc">
        <div class="login-tips" v-if="localStore.innerWidth > 768">
          <p class="tip-title">看看宇宙</p>
          <p class="tip-subtitle">点亮品牌之光，引领宣传、引流与获客新潮流</p>
        </div>
        <div class="login-form">
          <div class="tabs f-r-dc" v-if="current_tab != 2">
            <div
              class="tab-item cursor"
              :class="current_tab == index ? 'active' : ''"
              @click="tabChange(index)"
              v-for="(item, index) in tab_list"
              :key="index"
            >
              {{ item }}
            </div>
          </div>
          <div class="forget-title f-r-dc" v-if="current_tab == 2">
            <div class="back-box f-r-cc cursor" @click="current_tab = 1">
              <el-icon :size="20" color="#7285a0"><Back /></el-icon>
            </div>
            <span class="forget-text">找回密码</span>
          </div>
          <el-form
            ref="loginFormRef"
            style="width: 100%"
            :model="dataForm"
            :rules="rules"
            label-width="0"
            :hide-required-asterisk="true"
            class="login-form-content"
          >
            <el-form-item label="" prop="mobile" v-if="current_tab == 0">
              <el-input placeholder="请输入手机号" v-model="dataForm.mobile" />
            </el-form-item>
            <el-form-item label="" prop="account" v-if="current_tab == 1 || current_tab == 2">
              <el-input placeholder="请输入账号" v-model="dataForm.account" />
            </el-form-item>
            <el-form-item label="" prop="code" v-if="current_tab == 0 || current_tab == 2">
              <el-input v-model="dataForm.code" placeholder="请输入验证码">
                <template #suffix>
                  <span
                    class="code-suffix-text cursor"
                    @click.stop="getCodeBefore"
                    >{{
                      sms_info.codeDisabled
                        ? sms_info.countdownText
                        : '获取验证码'
                    }}</span
                  >
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="" prop="password" v-if="current_tab == 1 || current_tab == 2">
              <el-input placeholder="请输入密码" type="password" v-model="dataForm.password" />
            </el-form-item>
            <div class="forget cursor" @click="tabChange(2)" v-if="current_tab == 1">忘记密码</div>
          </el-form>
          <div class="login f-r-cc" v-if="current_tab == 2">
            <span @click="tabChange(0)" class="cursor">去登录</span>
          </div>

          <div class="agreement-tip f-r-cc">
            <span class="tip-d cursor-d">登录即代表同意</span>
            <span class="tip-a cursor" @click="toAgreement('user_agreement')">《用户协议》</span>
            <span class="tip-d cursor-d">和</span>
            <span class="tip-a cursor" @click="toAgreement('privacy_policy')">《隐私政策》</span>
          </div>

          <div class="login-btn f-r-cc cursor" @click="submit">
            {{ current_tab == 2 ? '提交' : '登录' }}
          </div>
        </div>
      </div>
    </div>
  </div>

  <Verify
    @success="successVerify"
    :captchaType="'blockPuzzle'"
    :imgSize="{ width: '310px', height: '155px' }"
    ref="verifyEl"
  ></Verify>

</template>

<script setup>
import { Back } from '@element-plus/icons-vue'
import { useUser } from '@/stores/user'
import Verify from '@/components/verify/verify.vue'
import { sendSms, login, resetPassword } from '@/api/index.js'
import { useLocal } from '@/stores/local'
const localStore = useLocal()
const router = useRouter()
const user_store = useUser()
const current_tab = ref(0)

const loginFormRef = ref(null)

const verifyEl = ref()
//短信校验
const captchaVerification = ref('')

const tab_list = ref(['短信登录', '账号登录'])

const dataForm = ref({
  mobile: '',
  code: '',
  account: '',
  password: ''
})

const sms_info = ref({
  codeDisabled: false,
  countdownText: '获取验证码',
  timer: null,
  currentTime: 60,
})

const loginRules = ref({
  phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
  code: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
})
const accountRules = ref({
  account: [{ required: true, message: '请输入账号', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
})
const forgetRules = ref({
  phone: [{ required: true, message: '请输入账号', trigger: 'blur' }],
  code: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
})

const rules = computed(() => {
  return current_tab.value === 0
    ? loginRules.value
    : current_tab.value === 1
    ? accountRules.value
    : forgetRules.value
})

// 跳转到APP下载
function download() {
  router.push({
    name: 'Downloads'
  })
}

// 路由跳转
function toPage (name) {
  router.push({ name })
}

// 协议
function toAgreement (name) {
  router.push({ name: 'Agreement', query: { type: name } })
}

function tabChange(index) {
  current_tab.value = index
  setTimeout(() => {
    loginFormRef.value.resetFields()
  })
}

function countdown() {
  sms_info.value.codeDisabled = true
  sms_info.value.timer = setInterval(() => {
    sms_info.value.currentTime -= 1
    sms_info.value.countdownText = `${sms_info.value.currentTime} S`
    if (sms_info.value.currentTime <= 0) {
      clearInterval(sms_info.value.timer)
      sms_info.value.currentTime = 60
      sms_info.value.codeDisabled = false
    }
  }, 1000)
}

function getCodeBefore() {
  if (sms_info.value.codeDisabled) return
  if (current_tab.value == 0 && !dataForm.value.mobile) {
    ElMessage.info('请输入手机号')
    return
  }
  if (current_tab.value == 2 && !dataForm.value.account) {
    ElMessage.info('请输入账号')
    return
  }
  verifyEl.value.show()
}

async function getCode() {
  let res = await sendSms({
    mobile: dataForm.value.mobile,
    event: 'login',
    captchaVerification: captchaVerification.value
  })
  ElMessage.info(res.msg || '验证码发送成功')
  if (res.msg && res.msg != '滑块验证失败，请重新验证') {
    countdown()
  }
}

// 图形校验成功
const successVerify = (data) => {
  captchaVerification.value = data.captchaVerification
  verifyEl.value.hide()
  getCode()
}

async function submit() {
  await loginFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      let params = {}
      let { mobile, code, account, password } = dataForm.value
      if (current_tab.value == 0) {
        // 验证码登录
        params = {
          code,
          mobile,
          type: 'code'
        }
      } else if (current_tab.value == 1) {
        // 密码登录
        params = {
          mobile: account,
          password,
          type: 'pwd'
        }
      } else if (current_tab.value == 2) {
        // 用户重置登录密码
        params = {
          mobile: account,
          code,
          password
        }
      }
      if (current_tab.value == 2) {
        let res = await resetPassword(params)
        current_tab.value = 0
        ElMessage.success('重置成功')
      } else {
        let res = await login(params)
        if (res.msg) {
          ElMessage.info(res.msg)
          return
        }
        localStorage.setItem('user_info', JSON.stringify(res.data))
        localStorage.setItem('token', res.data.token)
        user_store.logIn(res.data)
        user_store.getUserInfoApi()
        router.push({
          name: 'Home'
        })
      }
    } else {
    }
  })
}
</script>
<style scoped lang="less">
@import './index.less';
@media screen and (max-width: 768px) {
  @import './mobile/index.less';
}
</style>
